// UI 事件处理模块实现

#include "../output/ui.h"        // 包含SquareLine Studio生成的UI头文件
#include "../inc/ui_handlers.h"  // 包含本模块的头文件
#include "../inc/user_auth.h"    // 包含用户认证模块头文件
#include "../inc/movie_ticket.h" // 包含电影票务模块头文件
#include "../inc/ticket_print.h" // 包含出票模块头文件

#include <stdio.h>  // 用于printf
#include <string.h> // 用于字符串操作，如strcmp
#include <stdlib.h> // 用于 atof

// 全局变量，用于跟踪当前活动的键盘和文本区域
static lv_obj_t * current_active_keyboard = NULL;
static lv_obj_t * current_active_textarea = NULL;

// 显示消息提示框
void show_message_box(const char * title, const char * message, lv_obj_t * msg_panel, lv_obj_t * msg_title_label,
                      lv_obj_t * msg_message_label)
{
    printf("尝试显示消息框：标题='%s', 消息='%s'\n", title, message);
    fflush(stdout);

    if(msg_panel == NULL || msg_title_label == NULL || msg_message_label == NULL) {
        printf("错误：传入的弹窗UI元素为NULL，无法显示消息框。请检查SquareLine Studio中弹窗组件的名称和链接。\n");
        fflush(stdout);
        printf("Fallback message: Title='%s', Message='%s'\n", title, message);
        return;
    }

    lv_label_set_text(msg_title_label, title);
    lv_label_set_text(msg_message_label, message);

    lv_obj_clear_flag(msg_panel, LV_OBJ_FLAG_HIDDEN);
    lv_obj_move_foreground(msg_panel);

    printf("消息框已显示。\n");
    fflush(stdout);
}

// 隐藏当前活动的键盘
static void hide_active_keyboard(void)
{
    if(current_active_keyboard) {
        lv_obj_add_flag(current_active_keyboard, LV_OBJ_FLAG_HIDDEN);
        lv_keyboard_set_textarea(current_active_keyboard, NULL);
        current_active_keyboard = NULL;
    }
    if(current_active_textarea) {
        lv_obj_clear_state(current_active_textarea, LV_STATE_FOCUSED);
        current_active_textarea = NULL;
    }
}

// 显示指定键盘并关联文本区域
static void show_keyboard_for_textarea(lv_obj_t * keyboard, lv_obj_t * textarea)
{
    hide_active_keyboard();
    current_active_keyboard = keyboard;
    current_active_textarea = textarea;
    lv_obj_clear_flag(keyboard, LV_OBJ_FLAG_HIDDEN);
    lv_keyboard_set_textarea(keyboard, textarea);
    lv_obj_add_state(textarea, LV_STATE_FOCUSED);
}

// 检查 ancestor 是否是 obj 的祖先 (包括 obj 自身)
static bool is_ancestor_manual(lv_obj_t * ancestor, lv_obj_t * obj)
{
    if(ancestor == NULL || obj == NULL) {
        return false;
    }
    if(ancestor == obj) {
        return true;
    }
    lv_obj_t * parent = lv_obj_get_parent(obj);
    while(parent != NULL) {
        if(parent == ancestor) {
            return true;
        }
        parent = lv_obj_get_parent(parent);
    }
    return false;
}

// 屏幕点击事件回调 (用于点击外部隐藏键盘和弹窗)
void screen_clicked_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        lv_obj_t * target = lv_event_get_target(e);

        bool clicked_on_keyboard_area = false;
        if(current_active_keyboard) {
            if(is_ancestor_manual(current_active_keyboard, target)) {
                clicked_on_keyboard_area = true;
            }
        }

        bool clicked_on_textarea_area = false;
        if(current_active_textarea) {
            if(is_ancestor_manual(current_active_textarea, target)) {
                clicked_on_textarea_area = true;
            }
        }

        if(!clicked_on_keyboard_area && !clicked_on_textarea_area) {
            hide_active_keyboard();
        }

        // --- 处理消息框的隐藏逻辑 ---
        if(ui_PanelMessageBox && !lv_obj_has_flag(ui_PanelMessageBox, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelMessageBox, target)) {
                lv_obj_add_flag(ui_PanelMessageBox, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏登录界面消息框。\n");
                fflush(stdout);
            }
        } else if(ui_PanelMessageBoxReg && !lv_obj_has_flag(ui_PanelMessageBoxReg, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelMessageBoxReg, target)) {
                lv_obj_add_flag(ui_PanelMessageBoxReg, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏注册界面消息框。\n");
                fflush(stdout);
            }
        } else if(ui_PanelHomeMessageBox && !lv_obj_has_flag(ui_PanelHomeMessageBox, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelHomeMessageBox, target)) {
                lv_obj_add_flag(ui_PanelHomeMessageBox, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏主界面消息框。\n");
                fflush(stdout);
            }
        } else if(ui_PanelMovieSelectionMessageBox &&
                  !lv_obj_has_flag(ui_PanelMovieSelectionMessageBox, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelMovieSelectionMessageBox, target)) {
                lv_obj_add_flag(ui_PanelMovieSelectionMessageBox, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏电影选择界面消息框。\n");
                fflush(stdout);
            }
        } else if(ui_PanelSessionSelection && !lv_obj_has_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelSessionSelection, target)) {
                lv_obj_add_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏场次选择弹窗。\n");
                fflush(stdout);
                g_selected_movie_id[0]   = '\0';
                g_selected_session_id[0] = '\0';
            }
        } else if(ui_PanelSeatMessageBox && !lv_obj_has_flag(ui_PanelSeatMessageBox, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelSeatMessageBox, target)) {
                lv_obj_add_flag(ui_PanelSeatMessageBox, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏选座界面消息框。\n");
                fflush(stdout);
            }
        } else if(ui_PanelPrintTicketMessageBox &&
                  !lv_obj_has_flag(ui_PanelPrintTicketMessageBox, LV_OBJ_FLAG_HIDDEN)) {
            if(!is_ancestor_manual(ui_PanelPrintTicketMessageBox, target)) {
                lv_obj_add_flag(ui_PanelPrintTicketMessageBox, LV_OBJ_FLAG_HIDDEN);
                printf("点击外部，隐藏出票界面消息框。\n");
                fflush(stdout);
            }
        }
    }
}

// =============================================================================
// 登录界面输入框点击事件回调
// =============================================================================

void username_textarea_clicked_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        show_keyboard_for_textarea(ui_KeyboardLogin, ui_user);
    }
}

void password_textarea_clicked_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        show_keyboard_for_textarea(ui_KeyboardLogin, ui_password);
    }
}

// =============================================================================
// 注册界面输入框点击事件回调
// =============================================================================

void reg_username_textarea_clicked_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        show_keyboard_for_textarea(ui_KeyboardRegister, ui_user1);
    }
}

void reg_password_textarea_clicked_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        show_keyboard_for_textarea(ui_KeyboardRegister, ui_password1);
    }
}

void repeat_password_textarea_clicked_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        show_keyboard_for_textarea(ui_KeyboardRegister, ui_password2);
    }
}

// =============================================================================
// 弹窗关闭按钮事件回调
// =============================================================================

void message_box_close_btn_event_cb(lv_event_t * e)
{
    printf("消息框关闭按钮事件被触发 (此函数应不再被直接调用)。\n");
    fflush(stdout);
    if(ui_PanelMessageBox && !lv_obj_has_flag(ui_PanelMessageBox, LV_OBJ_FLAG_HIDDEN)) {
        lv_obj_add_flag(ui_PanelMessageBox, LV_OBJ_FLAG_HIDDEN);
    } else if(ui_PanelMessageBoxReg && !lv_obj_has_flag(ui_PanelMessageBoxReg, LV_OBJ_FLAG_HIDDEN)) {
        lv_obj_add_flag(ui_PanelMessageBoxReg, LV_OBJ_FLAG_HIDDEN);
    } else if(ui_PanelPrintTicketMessageBox && !lv_obj_has_flag(ui_PanelPrintTicketMessageBox, LV_OBJ_FLAG_HIDDEN)) {
        lv_obj_add_flag(ui_PanelPrintTicketMessageBox, LV_OBJ_FLAG_HIDDEN);
    }
}

void movie_selection_message_box_close_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了电影选择界面消息框，隐藏它。\n");
        fflush(stdout);
        if(ui_PanelMovieSelectionMessageBox) {
            lv_obj_add_flag(ui_PanelMovieSelectionMessageBox, LV_OBJ_FLAG_HIDDEN);
        }
    }
}

void seat_message_box_close_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了选座界面消息框，隐藏它。\n");
        fflush(stdout);
        if(ui_PanelSeatMessageBox) {
            lv_obj_add_flag(ui_PanelSeatMessageBox, LV_OBJ_FLAG_HIDDEN);
        }
    }
}

void print_ticket_message_box_close_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了出票界面消息框，隐藏它。\n");
        fflush(stdout);
        if(ui_PanelPrintTicketMessageBox) {
            lv_obj_add_flag(ui_PanelPrintTicketMessageBox, LV_OBJ_FLAG_HIDDEN);
        }
    }
}

// =============================================================================
// 按钮事件回调
// =============================================================================

void login_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '登录' 按钮 - 开始处理\n");
        fflush(stdout);
        hide_active_keyboard();
        printf("键盘已隐藏\n");
        fflush(stdout);

        const char * username = lv_textarea_get_text(ui_user);
        const char * password = lv_textarea_get_text(ui_password);
        printf("获取到用户名: %s, 密码: %s\n", username, password);
        fflush(stdout);

        if(username == NULL || password == NULL) {
            show_message_box("错误", "输入字段未准备好。", ui_PanelMessageBox, ui_LabelMessageBoxTitle,
                             ui_LabelMessageBoxMessage);
            printf("用户名或密码指针为NULL，避免段错误\n");
            fflush(stdout);
            return;
        }

        if(strlen(username) == 0 || strlen(password) == 0) {
            show_message_box("错误", "用户名和密码不能为空！", ui_PanelMessageBox, ui_LabelMessageBoxTitle,
                             ui_LabelMessageBoxMessage);
            printf("用户名或密码为空，显示错误消息\n");
            fflush(stdout);
            return;
        }

        User g_users[100];                          // 临时数组，只在函数内部使用
        int g_num_users = load_users(g_users, 100); // 从 user_auth 模块加载用户
        printf("加载用户数量: %d\n", g_num_users);
        fflush(stdout);
        if(g_num_users == -1) {
            show_message_box("错误", "无法读取用户数据文件！", ui_PanelMessageBox, ui_LabelMessageBoxTitle,
                             ui_LabelMessageBoxMessage);
            printf("显示文件读取错误消息\n");
            fflush(stdout);
            return;
        }

        if(verify_credentials(username, password, g_users, g_num_users)) { // 使用 user_auth 模块验证凭据
            printf("登录成功，切换界面。\n");
            fflush(stdout);
            lv_scr_load(ui_Home);
            strncpy(g_logged_in_username, username, sizeof(g_logged_in_username) - 1);
            g_logged_in_username[sizeof(g_logged_in_username) - 1] = '\0';
            printf("登录成功！g_logged_in_username 已设置为: '%s'\n", g_logged_in_username);
            fflush(stdout);
            lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
            printf("切换到主功能界面\n");
            fflush(stdout);
            lv_textarea_set_text(ui_user, "");
            lv_textarea_set_text(ui_password, "");

        } else {
            show_message_box("错误", "账号或密码错误！", ui_PanelMessageBox, ui_LabelMessageBoxTitle,
                             ui_LabelMessageBoxMessage);
            printf("登录失败，显示错误消息\n");
            fflush(stdout);
        }
    }
}

void register_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '注册' 按钮 (从登录界面)\n");
        fflush(stdout);
        hide_active_keyboard();
        lv_scr_load(ui_UserRegister);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换到注册屏幕\n");
        fflush(stdout);
        lv_textarea_set_text(ui_user1, "");
        lv_textarea_set_text(ui_password1, "");
        lv_textarea_set_text(ui_password2, "");
    }
}

void confirm_register_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '确认注册' 按钮\n");
        fflush(stdout);
        hide_active_keyboard();
        printf("键盘已隐藏\n");
        fflush(stdout);

        const char * reg_username    = lv_textarea_get_text(ui_user1);
        const char * reg_password    = lv_textarea_get_text(ui_password1);
        const char * repeat_password = lv_textarea_get_text(ui_password2);
        printf("获取到注册用户名: %s\n", reg_username);
        fflush(stdout);

        if(reg_username == NULL || reg_password == NULL || repeat_password == NULL) {
            show_message_box("错误", "内部错误：输入字段未准备好。", ui_PanelMessageBoxReg, ui_LabelMessageBoxTitleReg,
                             ui_LabelMessageBoxMessageReg);
            printf("注册输入指针为NULL，避免段错误\n");
            fflush(stdout);
            return;
        }

        if(strlen(reg_username) == 0 || strlen(reg_password) == 0 || strlen(repeat_password) == 0) {
            show_message_box("错误", "用户名或密码不能为空！", ui_PanelMessageBoxReg, ui_LabelMessageBoxTitleReg,
                             ui_LabelMessageBoxMessageReg);
            printf("显示空输入错误消息\n");
            fflush(stdout);
            return;
        }

        if(strcmp(reg_password, repeat_password) != 0) {
            show_message_box("错误", "两次密码输入不一致，请重新输入！", ui_PanelMessageBoxReg,
                             ui_LabelMessageBoxTitleReg, ui_LabelMessageBoxMessageReg);
            printf("显示密码不一致错误消息\n");
            fflush(stdout);
            lv_textarea_set_text(ui_password1, "");
            lv_textarea_set_text(ui_password2, "");
            return;
        }

        User g_users[100];                          // 临时数组
        int g_num_users = load_users(g_users, 100); // 从 user_auth 模块加载用户
        printf("加载用户数量: %d\n", g_num_users);
        fflush(stdout);
        if(g_num_users == -1) {
            show_message_box("错误", "无法读取用户数据文件！", ui_PanelMessageBoxReg, ui_LabelMessageBoxTitleReg,
                             ui_LabelMessageBoxMessageReg);
            printf("显示文件读取错误消息\n");
            fflush(stdout);
            return;
        }

        if(is_username_exists(reg_username, g_users, g_num_users)) { // 使用 user_auth 模块检查用户名
            show_message_box("错误", "该用户名已被使用！", ui_PanelMessageBoxReg, ui_LabelMessageBoxTitleReg,
                             ui_LabelMessageBoxMessageReg);
            printf("显示用户名已存在错误消息\n");
            fflush(stdout);
            lv_textarea_set_text(ui_user1, "");
            return;
        }

        User new_user;
        strncpy(new_user.username, reg_username, sizeof(new_user.username) - 1);
        new_user.username[sizeof(new_user.username) - 1] = '\0';
        strncpy(new_user.password, reg_password, sizeof(new_user.password) - 1);
        new_user.password[sizeof(new_user.password) - 1] = '\0';

        if(append_user(&new_user) == 0) { // 使用 user_auth 模块追加用户
            printf("注册成功，切换界面。\n");
            fflush(stdout);
            lv_scr_load(ui_UserLogin);
            lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
            printf("切换回登录屏幕\n");
            fflush(stdout);
            lv_textarea_set_text(ui_user, "");
            lv_textarea_set_text(ui_password, "");
        } else {
            show_message_box("错误", "注册失败，请重试！", ui_PanelMessageBoxReg, ui_LabelMessageBoxTitleReg,
                             ui_LabelMessageBoxMessageReg);
            printf("注册失败，显示错误消息\n");
            fflush(stdout);
        }
    }
}

void cancel_register_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '取消' 按钮 (从注册界面)\n");
        fflush(stdout);
        hide_active_keyboard();
        lv_scr_load(ui_UserLogin);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换回登录屏幕\n");
        fflush(stdout);
        lv_textarea_set_text(ui_user, "");
        lv_textarea_set_text(ui_password, "");
    }
}

void logout_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '返回登录' 按钮。\n");
        fflush(stdout);
        hide_active_keyboard();
        lv_scr_load(ui_UserLogin);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换回登录屏幕。\n");
        fflush(stdout);
        lv_textarea_set_text(ui_user, "");
        lv_textarea_set_text(ui_password, "");
        g_logged_in_username[0] = '\0'; // 清空登录用户名
    }
}

void buy_ticket_main_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '购票' 按钮 (主功能界面)\n");
        fflush(stdout);
        hide_active_keyboard();

        lv_scr_load(ui_ScreenMovieSelection);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换到电影选择界面\n");
        fflush(stdout);
    }
}

void movie_selection_back_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了电影选择界面的 '返回' 按钮。\n");
        fflush(stdout);
        hide_active_keyboard();
        lv_scr_load(ui_Home);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换回主界面。\n");
        fflush(stdout);
    }
}

// =============================================================================
// 电影选择界面购票按钮回调
// =============================================================================

void buy_wuming_movie_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '无名之辈' 购票按钮。\n");
        fflush(stdout);
        strncpy(g_selected_movie_id, "M001", sizeof(g_selected_movie_id) - 1);
        g_selected_movie_id[sizeof(g_selected_movie_id) - 1] = '\0';

        if(ui_PanelSessionSelection) {
            lv_obj_clear_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            lv_obj_move_foreground(ui_PanelSessionSelection);
            printf("显示场次选择弹窗。\n");
            fflush(stdout);
        } else {
            printf("错误：无法显示场次选择弹窗。\n");
            fflush(stdout);
        }
    }
}

void buy_tangrenjie_movie_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '唐人街探案3' 购票按钮。\n");
        fflush(stdout);
        strncpy(g_selected_movie_id, "M002", sizeof(g_selected_movie_id) - 1);
        g_selected_movie_id[sizeof(g_selected_movie_id) - 1] = '\0';

        if(ui_PanelSessionSelection) {
            lv_obj_clear_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            lv_obj_move_foreground(ui_PanelSessionSelection);
            printf("显示场次选择弹窗。\n");
            fflush(stdout);
        } else {
            printf("错误：无法显示场次选择弹窗。\n");
            fflush(stdout);
        }
    }
}

void buy_liulangdiqiu_movie_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '流浪地球2' 购票按钮。\n");
        fflush(stdout);
        strncpy(g_selected_movie_id, "M003", sizeof(g_selected_movie_id) - 1);
        g_selected_movie_id[sizeof(g_selected_movie_id) - 1] = '\0';

        if(ui_PanelSessionSelection) {
            lv_obj_clear_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            lv_obj_move_foreground(ui_PanelSessionSelection);
            printf("显示场次选择弹窗。\n");
            fflush(stdout);
        } else {
            printf("错误：无法显示场次选择弹窗。\n");
            fflush(stdout);
        }
    }
}

// =============================================================================
// 场次选择弹窗按钮回调
// =============================================================================

// 辅助函数：初始化选座界面的UI元素和座位图
static void initialize_seat_selection_ui_elements_logic()
{
    printf("开始初始化选座界面UI和座位。\n");
    fflush(stdout);

    if(ui_PanelSeatMapContainer == NULL) {
        printf("错误：无法清空旧座位或创建新座位。\n");
        fflush(stdout);
        show_message_box("错误", "座位图容器未准备好！", ui_PanelSeatMessageBox, ui_LabelSeatMessageBoxTitle,
                         ui_LabelSeatMessageBoxMessage);
        return;
    }
    lv_obj_clean(ui_PanelSeatMapContainer);
    printf("座位图容器已清空。\n");
    fflush(stdout);

    const Movie * selected_movie               = get_movie_by_id(g_selected_movie_id);     // 使用 movie_ticket 模块
    const MovieSession * selected_session_info = get_session_by_id(g_selected_session_id); // 使用 movie_ticket 模块

    if(selected_movie == NULL || selected_session_info == NULL) {
        printf("错误：电影ID '%s' 或场次ID '%s' 信息丢失！无法加载座位图。\n", g_selected_movie_id,
               g_selected_session_id);
        fflush(stdout);
        show_message_box("错误", "电影或场次信息丢失！", ui_PanelSeatMessageBox, ui_LabelSeatMessageBoxTitle,
                         ui_LabelSeatMessageBoxMessage);
        lv_scr_load(ui_ScreenMovieSelection);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        return;
    }
    printf("已获取电影 '%s', 场次 '%s' 信息。\n", selected_movie->name, selected_session_info->show_time);
    fflush(stdout);

    if(ui_LabelSelectedMovieName) {
        char info_text[256];
        snprintf(info_text, sizeof(info_text), "电影：%s", selected_movie->name);
        lv_label_set_text(ui_LabelSelectedMovieName, info_text);
    } else {
        printf("警告：ui_LabelSelectedMovieName 为 NULL。\n");
        fflush(stdout);
    }

    if(ui_LabelSelectedSessionDetails) {
        char info_text[256];
        snprintf(info_text, sizeof(info_text), "场次：%s (%s)", selected_session_info->show_time,
                 selected_session_info->type);
        lv_label_set_text(ui_LabelSelectedSessionDetails, info_text);
    } else {
        printf("警告：ui_LabelSelectedSessionDetails 为 NULL。\n");
        fflush(stdout);
    }

    if(ui_LabelSelectedHallNumber) {
        char info_text[256];
        snprintf(info_text, sizeof(info_text), "影厅：%s", selected_session_info->hall_number);
        lv_label_set_text(ui_LabelSelectedHallNumber, info_text);
    } else {
        printf("警告：ui_LabelSelectedHallNumber 为 NULL。\n");
        fflush(stdout);
    }

    if(ui_LabelTicketUnitPrice) {
        char info_text[256];
        snprintf(info_text, sizeof(info_text), "票价：%.2f元/张", selected_session_info->price);
        lv_label_set_text(ui_LabelTicketUnitPrice, info_text);
    } else {
        printf("警告：ui_LabelTicketUnitPrice 为 NULL。\n");
        fflush(stdout);
    }

    printf("顶部信息面板已更新。\n");
    fflush(stdout);

    load_seat_map(g_selected_session_id, g_current_seat_map, &g_current_seat_map_rows,
                  &g_current_seat_map_cols); // 使用 movie_ticket 模块
    printf("座位图已从文件加载。\n");
    fflush(stdout);

    g_num_selected_seats  = 0;
    g_current_total_price = 0.0f;

    const lv_coord_t SEAT_BTN_WIDTH  = 55;
    const lv_coord_t SEAT_BTN_HEIGHT = 45;
    const lv_coord_t SEAT_BTN_RADIUS = 5;
    const lv_opa_t SEAT_BTN_OPA      = 255;

    const lv_color_t SEAT_COLOR_AVAILABLE = lv_color_hex(0x2ECC71); 
    const lv_color_t SEAT_COLOR_SELECTED  = lv_color_hex(0x3498DB);  
    const lv_color_t SEAT_COLOR_SOLD      = lv_color_hex(0xE74C3C);

    char seat_name[5];
    for(int r = 0; r < 6; r++) {
        for(int c = 0; c < 12; c++) {
            lv_obj_t * seat_btn = lv_btn_create(ui_PanelSeatMapContainer);

            lv_obj_set_size(seat_btn, SEAT_BTN_WIDTH, SEAT_BTN_HEIGHT);
            lv_obj_set_style_radius(seat_btn, SEAT_BTN_RADIUS, LV_PART_MAIN);
            lv_obj_set_style_bg_opa(seat_btn, SEAT_BTN_OPA, LV_PART_MAIN);
            lv_obj_clear_flag(seat_btn, LV_OBJ_FLAG_HIDDEN);

            snprintf(seat_name, sizeof(seat_name), "%c%d", 'A' + r, c + 1);
            lv_obj_t * seat_label = lv_label_create(seat_btn);
            lv_label_set_text(seat_label, seat_name);
            lv_obj_center(seat_label);

            lv_obj_set_style_text_color(seat_label, lv_color_white(), LV_PART_MAIN);
            lv_obj_set_style_text_font(seat_label, &ui_font_size16, LV_PART_MAIN);

            if(g_current_seat_map[r][c] == SEAT_SOLD) {
                lv_obj_add_state(seat_btn, LV_STATE_DISABLED);
                lv_obj_set_style_bg_color(seat_btn, SEAT_COLOR_SOLD, LV_PART_MAIN | LV_STATE_DISABLED);
            } else {
                lv_obj_add_event_cb(seat_btn, seat_button_clicked_cb, LV_EVENT_CLICKED, (void *)(intptr_t)(r * 12 + c));
                lv_obj_set_style_bg_color(seat_btn, SEAT_COLOR_AVAILABLE, LV_PART_MAIN);
                lv_obj_set_style_bg_color(seat_btn, SEAT_COLOR_SELECTED, LV_PART_MAIN | LV_STATE_CHECKED);
            }
        }
    }
    lv_obj_update_layout(ui_PanelSeatMapContainer);
    printf("座位按钮已动态生成并更新布局。\n");
    fflush(stdout);

    if(ui_LabelSelectedSeatsDisplay) {
        lv_label_set_text(ui_LabelSelectedSeatsDisplay, "已选：无");
    } else {
        printf("警告：ui_LabelSelectedSeatsDisplay 为 NULL。\n");
        fflush(stdout);
    }

    if(ui_LabelTotalPrice) {
        lv_label_set_text(ui_LabelTotalPrice, "总价：0.00元");
    } else {
        printf("警告：ui_LabelTotalPrice 为 NULL。\n");
        fflush(stdout);
    }
    printf("底部信息面板已初始化。\n");
    fflush(stdout);
}

void select_session_1030_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("选择了场次 '10:30 (普通场)'。\n");
        fflush(stdout);
        snprintf(g_selected_session_id, sizeof(g_selected_session_id), "%s_S001", g_selected_movie_id);
        g_selected_session_id[sizeof(g_selected_session_id) - 1] = '\0';
        printf("已设置复合场次ID: '%s'\n", g_selected_session_id);

        if(ui_PanelSessionSelection) {
            lv_obj_add_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            printf("隐藏场次选择弹窗。\n");
            fflush(stdout);
        }

        lv_scr_load(ui_ScreenSeatSelection);
        initialize_seat_selection_ui_elements_logic();
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换到选座界面。\n");
        fflush(stdout);
    }
}

void select_session_1400_3d_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("选择了场次 '14:00 (3D MAX场)'。\n");
        fflush(stdout);
        snprintf(g_selected_session_id, sizeof(g_selected_session_id), "%s_S002", g_selected_movie_id);
        g_selected_session_id[sizeof(g_selected_session_id) - 1] = '\0';
        printf("已设置复合场次ID: '%s'\n", g_selected_session_id);

        if(ui_PanelSessionSelection) {
            lv_obj_add_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            printf("隐藏场次选择弹窗。\n");
            fflush(stdout);
        }

        lv_scr_load(ui_ScreenSeatSelection);
        initialize_seat_selection_ui_elements_logic();
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换到选座界面。\n");
        fflush(stdout);
    }
}

void select_session_1830_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("选择了场次 '18:30 (普通场)'。\n");
        fflush(stdout);
        snprintf(g_selected_session_id, sizeof(g_selected_session_id), "%s_S003", g_selected_movie_id);
        g_selected_session_id[sizeof(g_selected_session_id) - 1] = '\0';
        printf("已设置复合场次ID: '%s'\n", g_selected_session_id);

        if(ui_PanelSessionSelection) {
            lv_obj_add_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            printf("隐藏场次选择弹窗。\n");
            fflush(stdout);
        }

        lv_scr_load(ui_ScreenSeatSelection);
        initialize_seat_selection_ui_elements_logic();
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换到选座界面。\n");
        fflush(stdout);
    }
}

void session_selection_back_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了场次选择弹窗的 '返回' 按钮。\n");
        fflush(stdout);
        if(ui_PanelSessionSelection) {
            lv_obj_add_flag(ui_PanelSessionSelection, LV_OBJ_FLAG_HIDDEN);
            printf("隐藏场次选择弹窗。\n");
            fflush(stdout);
        }
        g_selected_movie_id[0]   = '\0';
        g_selected_session_id[0] = '\0';
    }
}

// 出票按钮点击事件回调 (主功能界面)
void print_ticket_main_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '出票' 按钮 (主功能界面)。\n");
        fflush(stdout);
        hide_active_keyboard();

        if(strlen(g_logged_in_username) == 0) {
            show_message_box("提示", "请先登录才能查看电影票！", ui_PanelHomeMessageBox, ui_LabelHomeMessageBoxTitle,
                             ui_LabelHomeMessageBoxMessage);
            printf("用户未登录，无法进入出票界面。\n");
            fflush(stdout);
            return;
        }

        g_num_user_tickets =
            load_purchase_records(g_logged_in_username, g_user_tickets, MAX_PURCHASE_RECORDS); // 使用 ticket_print 模块
        if(g_num_user_tickets == -1) {
            show_message_box("错误", "加载购票记录失败！", ui_PanelHomeMessageBox, ui_LabelHomeMessageBoxTitle,
                             ui_LabelHomeMessageBoxMessage);
            printf("加载购票记录失败。\n");
            fflush(stdout);
            return;
        }

        if(ui_PanelTicketListContainer) {
            lv_obj_clean(ui_PanelTicketListContainer);
        } else {
            printf("错误：ui_PanelTicketListContainer 为 NULL，无法清空列表。\n");
            fflush(stdout);
            return;
        }

        if(g_num_user_tickets == 0) {
            lv_obj_t * no_ticket_label = lv_label_create(ui_PanelTicketListContainer);
            lv_label_set_text(no_ticket_label, "您还没有购买任何电影票。");
            lv_obj_set_style_text_color(no_ticket_label, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
            lv_obj_set_style_text_font(no_ticket_label, &ui_font_size20, LV_PART_MAIN);
            lv_obj_set_align(no_ticket_label, LV_ALIGN_CENTER);
            printf("没有购票记录，显示提示。\n");
            fflush(stdout);
        } else {
            for(int i = 0; i < g_num_user_tickets; i++) {
                lv_obj_t * ticket_panel = lv_obj_create(ui_PanelTicketListContainer);
                lv_obj_set_width(ticket_panel, 690);
                lv_obj_set_height(ticket_panel, 100);
                lv_obj_clear_flag(ticket_panel, LV_OBJ_FLAG_SCROLLABLE);
                lv_obj_set_style_radius(ticket_panel, 10, LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_bg_color(ticket_panel, lv_color_hex(0x34495E), LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_bg_opa(ticket_panel, 255, LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_pad_left(ticket_panel, 10, LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_pad_right(ticket_panel, 10, LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_pad_top(ticket_panel, 10, LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_pad_bottom(ticket_panel, 10, LV_PART_MAIN | LV_STATE_DEFAULT);

                g_user_tickets[i].ui_panel = ticket_panel;

                lv_obj_t * label_movie_info = lv_label_create(ticket_panel);
                char movie_info_text[128];
                char session_details[64];
                get_session_details_by_composite_id(g_user_tickets[i].session_id, session_details,
                                                    sizeof(session_details)); // 使用 movie_ticket 模块
                snprintf(movie_info_text, sizeof(movie_info_text), "%s - %s",
                         get_movie_name_by_id(g_user_tickets[i].movie_id), session_details); // 使用 movie_ticket 模块
                lv_label_set_text(label_movie_info, movie_info_text);
                lv_obj_set_style_text_color(label_movie_info, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
                lv_obj_set_style_text_font(label_movie_info, &ui_font_size26, LV_PART_MAIN);
                lv_obj_set_x(label_movie_info, 5);
                lv_obj_set_y(label_movie_info, 4);

                lv_obj_t * label_hall_seat = lv_label_create(ticket_panel);
                char hall_seat_text[64];
                const MovieSession * session_obj =
                    get_session_by_id(g_user_tickets[i].session_id); // 使用 movie_ticket 模块
                snprintf(hall_seat_text, sizeof(hall_seat_text), "影厅：%s                     座位：%s",
                         session_obj ? session_obj->hall_number : "未知", g_user_tickets[i].seat_info);
                lv_label_set_text(label_hall_seat, hall_seat_text);
                lv_obj_set_style_text_color(label_hall_seat, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
                lv_obj_set_style_text_font(label_hall_seat, &ui_font_size26, LV_PART_MAIN);
                lv_obj_set_x(label_hall_seat, 5);
                lv_obj_set_y(label_hall_seat, 40);

                lv_obj_t * label_price = lv_label_create(ticket_panel);
                char price_text[32];
                snprintf(price_text, sizeof(price_text), "票价: %.2f 元", g_user_tickets[i].price);
                lv_label_set_text(label_price, price_text);
                lv_obj_set_style_text_color(label_price, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
                lv_obj_set_style_text_font(label_price, &ui_font_size26, LV_PART_MAIN);
                lv_obj_set_x(label_price, -10);
                lv_obj_set_y(label_price, 4);
                lv_obj_set_align(label_price, LV_ALIGN_TOP_RIGHT);

                lv_obj_t * checkbox = lv_switch_create(ticket_panel);
                lv_obj_set_width(checkbox, 70);
                lv_obj_set_height(checkbox, 30);
                lv_obj_set_align(checkbox, LV_ALIGN_BOTTOM_RIGHT);
                lv_obj_add_event_cb(checkbox, print_ticket_checkbox_event_cb, LV_EVENT_VALUE_CHANGED,
                                    (void *)(intptr_t)i);
            }
        }

        lv_obj_update_layout(ui_PanelTicketListContainer);
        lv_scr_load(ui_ScreenPrintTicket);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换到出票界面。\n");
        fflush(stdout);
    }
}

void movie_poster_scroll_end_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_SCROLL_END) {
        printf("电影海报滑动结束。\n");
        fflush(stdout);
    }
}

//座位按钮点击事件回调。处理座位选中/取消选中逻辑，更新已选座位列表和总价。
void seat_button_clicked_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        lv_obj_t * seat_btn = lv_event_get_target(e);
        int seat_index      = (int)(intptr_t)lv_event_get_user_data(e);
        int r               = seat_index / 12;
        int c               = seat_index % 12;

        const MovieSession * selected_session = get_session_by_id(g_selected_session_id); // 使用 movie_ticket 模块
        float unit_price                      = (selected_session != NULL) ? selected_session->price : 0.0f;

        if(g_current_seat_map[r][c] == SEAT_AVAILABLE) {
            if(lv_obj_has_state(seat_btn, LV_STATE_CHECKED)) {
                lv_obj_clear_state(seat_btn, LV_STATE_CHECKED);
                g_current_seat_map[r][c] = SEAT_AVAILABLE;
                g_current_total_price -= unit_price;

                for(int i = 0; i < g_num_selected_seats; i++) {
                    if(g_selected_seats_list[i].row == r && g_selected_seats_list[i].col == c) {
                        for(int j = i; j < g_num_selected_seats - 1; j++) {
                            g_selected_seats_list[j] = g_selected_seats_list[j + 1];
                        }
                        g_num_selected_seats--;
                        break;
                    }
                }
                printf("取消选中座位 %c%d。\n", 'A' + r, c + 1);
            } else {
                if(g_num_selected_seats < (6 * 12)) {
                    lv_obj_add_state(seat_btn, LV_STATE_CHECKED);
                    g_current_seat_map[r][c] = SEAT_SELECTED;
                    g_current_total_price += unit_price;

                    g_selected_seats_list[g_num_selected_seats].row     = r;
                    g_selected_seats_list[g_num_selected_seats].col     = c;
                    g_selected_seats_list[g_num_selected_seats].btn_obj = seat_btn;
                    g_num_selected_seats++;
                    printf("选中座位 %c%d。\n", 'A' + r, c + 1);
                } else {
                    show_message_box("提示", "已达到最大选座数量！", ui_PanelSeatMessageBox,
                                     ui_LabelSeatMessageBoxTitle, ui_LabelSeatMessageBoxMessage);
                    printf("达到最大选座数量。\n");
                }
            }

            char selected_seats_str[256] = "已选：";
            char temp_seat_str[5];
            for(int i = 0; i < g_num_selected_seats; i++) {
                snprintf(temp_seat_str, sizeof(temp_seat_str), "%c%d", 'A' + g_selected_seats_list[i].row,
                         g_selected_seats_list[i].col + 1);
                strcat(selected_seats_str, temp_seat_str);
                if(i < g_num_selected_seats - 1) {
                    strcat(selected_seats_str, ",");
                }
            }
            if(g_num_selected_seats == 0) {
                if(ui_LabelSelectedSeatsDisplay) lv_label_set_text(ui_LabelSelectedSeatsDisplay, "已选：无");
            } else {
                if(ui_LabelSelectedSeatsDisplay) lv_label_set_text(ui_LabelSelectedSeatsDisplay, selected_seats_str);
            }

            char total_price_str[32];
            snprintf(total_price_str, sizeof(total_price_str), "总价：%.2f元", g_current_total_price);
            if(ui_LabelTotalPrice) lv_label_set_text(ui_LabelTotalPrice, total_price_str);

            fflush(stdout);
        } else if(g_current_seat_map[r][c] == SEAT_SOLD) {
            show_message_box("提示", "该座位已售出，请选择其他座位。", ui_PanelSeatMessageBox,
                             ui_LabelSeatMessageBoxTitle, ui_LabelSeatMessageBoxMessage);
            printf("点击了已售座位 %c%d。\n", 'A' + r, c + 1);
            fflush(stdout);
        }
    }
}

void confirm_purchase_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '确认购买' 按钮。\n");
        fflush(stdout);

        printf("在确认购买时，g_logged_in_username 当前值为: '%s'\n", g_logged_in_username);
        fflush(stdout);

        if(g_num_selected_seats == 0) {
            show_message_box("提示", "请先选择座位！", ui_PanelSeatMessageBox, ui_LabelSeatMessageBoxTitle,
                             ui_LabelSeatMessageBoxMessage);
            printf("未选择座位。\n");
            fflush(stdout);
            return;
        }

        if(strlen(g_logged_in_username) == 0) {
            show_message_box("错误", "用户未登录，无法购票！", ui_PanelSeatMessageBox, ui_LabelSeatMessageBoxTitle,
                             ui_LabelSeatMessageBoxMessage);
            printf("用户未登录。\n");
            fflush(stdout);
            return;
        }

        char selected_seats_str[256] = "";
        char temp_seat_str[5];
        for(int i = 0; i < g_num_selected_seats; i++) {
            int r = g_selected_seats_list[i].row;
            int c = g_selected_seats_list[i].col;

            g_current_seat_map[r][c] = SEAT_SOLD;
            if(g_selected_seats_list[i].btn_obj) {
                lv_obj_add_state((lv_obj_t *)g_selected_seats_list[i].btn_obj, LV_STATE_DISABLED);
                lv_obj_clear_state((lv_obj_t *)g_selected_seats_list[i].btn_obj, LV_STATE_CHECKED);
                lv_obj_set_style_bg_color((lv_obj_t *)g_selected_seats_list[i].btn_obj, lv_color_hex(0xE74C3C),
                                          LV_PART_MAIN | LV_STATE_DISABLED);
            }

            snprintf(temp_seat_str, sizeof(temp_seat_str), "%c%d", 'A' + r, c + 1);
            strcat(selected_seats_str, temp_seat_str);
            if(i < g_num_selected_seats - 1) {
                strcat(selected_seats_str, ",");
            }
        }

        save_seat_map(g_selected_session_id, g_current_seat_map, g_current_seat_map_rows,
                      g_current_seat_map_cols); // 使用 movie_ticket 模块

        record_purchase_info(g_logged_in_username, g_selected_movie_id, g_selected_session_id, g_num_selected_seats,
                             selected_seats_str); // 使用 movie_ticket 模块

        char success_msg[256];
        snprintf(success_msg, sizeof(success_msg), "购买成功！\n共%d张票，总价%.2f元。", g_num_selected_seats,
                 g_current_total_price);
        show_message_box("购买成功", success_msg, ui_PanelSeatMessageBox, ui_LabelSeatMessageBoxTitle,
                         ui_LabelSeatMessageBoxMessage);
        printf("购买成功，已保存记录并更新座位图。\n");
        fflush(stdout);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);

        g_num_selected_seats  = 0;
        g_current_total_price = 0.0f;
        if(ui_LabelSelectedSeatsDisplay) lv_label_set_text(ui_LabelSelectedSeatsDisplay, "已选：无");
        if(ui_LabelTotalPrice) lv_label_set_text(ui_LabelTotalPrice, "总价：0.00元");
    }
}

void seat_selection_back_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了选座界面的 '返回' 按钮。\n");
        fflush(stdout);
        g_num_selected_seats     = 0;
        g_current_total_price    = 0.0f;
        g_selected_movie_id[0]   = '\0';
        g_selected_session_id[0] = '\0';

        lv_scr_load(ui_ScreenMovieSelection);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换回电影选择界面。\n");
        fflush(stdout);
    }
}

// =============================================================================
// 出票界面相关回调
// =============================================================================

void print_ticket_back_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了出票界面的 '返回' 按钮。\n");
        fflush(stdout);
        for(int i = 0; i < g_num_user_tickets; i++) {
            g_user_tickets[i].selected_for_print = false;
        }
        lv_scr_load(ui_Home);
        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
        printf("切换回主界面。\n");
        fflush(stdout);
    }
}

void print_ticket_checkbox_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_VALUE_CHANGED) {
        lv_obj_t * checkbox = lv_event_get_target(e);
        int ticket_index    = (int)(intptr_t)lv_event_get_user_data(e);

        if(ticket_index >= 0 && ticket_index < g_num_user_tickets) {
            bool is_checked                                 = lv_obj_has_state(checkbox, LV_STATE_CHECKED);
            g_user_tickets[ticket_index].selected_for_print = is_checked;
            printf("票号 '%s' 的选中状态变为：%s\n", g_user_tickets[ticket_index].ticket_id,
                   is_checked ? "选中" : "未选中");
            fflush(stdout);
        }
    }
}

static void print_animation_timer_cb(lv_timer_t * timer)
{
    static int progress            = 0;
    const char * status_messages[] = {"正在准备打印...", "正在连接打印机...", "正在打印电影票...", "打印完成！"};

    progress += 10;
    if(progress > 100) {
        progress = 100;
    }

    lv_bar_set_value(ui_ProgressBarPrint, progress, LV_ANIM_ON);

    if(progress <= 30) {
        lv_label_set_text(ui_LabelPrintStatus, status_messages[0]);
    } else if(progress <= 60) {
        lv_label_set_text(ui_LabelPrintStatus, status_messages[1]);
    } else if(progress <= 90) {
        lv_label_set_text(ui_LabelPrintStatus, status_messages[2]);
    } else {
        lv_label_set_text(ui_LabelPrintStatus, status_messages[3]);
    }

    if(progress >= 100) {
        lv_timer_del(timer);
        lv_obj_add_flag(ui_PanelPrintAnimation, LV_OBJ_FLAG_HIDDEN);
        printf("出票动画完成。\n");
        fflush(stdout);

        int removed_count = 0;
        for(int i = g_num_user_tickets - 1; i >= 0; i--) {
            if(g_user_tickets[i].selected_for_print) {
                if(remove_purchase_record(g_user_tickets[i].ticket_id) == 0) { // 使用 ticket_print 模块
                    if(g_user_tickets[i].ui_panel) {
                        lv_obj_del((lv_obj_t *)g_user_tickets[i].ui_panel); // 强制转换为 lv_obj_t*
                        g_user_tickets[i].ui_panel = NULL;
                    }
                    for(int j = i; j < g_num_user_tickets - 1; j++) {
                        g_user_tickets[j] = g_user_tickets[j + 1];
                    }
                    g_num_user_tickets--;
                    removed_count++;
                } else {
                    printf("错误：未能从文件中移除票号 '%s'。\n", g_user_tickets[i].ticket_id);
                    fflush(stdout);
                }
            }
        }
        lv_obj_update_layout(ui_PanelTicketListContainer);

        if(removed_count > 0) {
            show_message_box("成功", "电影票已成功出票！", ui_PanelPrintTicketMessageBox,
                             ui_LabelPrintTicketMessageBoxTitle, ui_LabelPrintTicketMessageBoxMessage);
            printf("成功出票 %d 张。\n", removed_count);
        } else {
            show_message_box("提示", "没有选中的电影票进行出票。", ui_PanelPrintTicketMessageBox,
                             ui_LabelPrintTicketMessageBoxTitle, ui_LabelPrintTicketMessageBoxMessage);
            printf("没有选中的电影票。\n");
        }
        fflush(stdout);

        if(g_num_user_tickets == 0) {
            lv_obj_clean(ui_PanelTicketListContainer);
            lv_obj_t * no_ticket_label = lv_label_create(ui_PanelTicketListContainer);
            lv_label_set_text(no_ticket_label, "您还没有购买任何电影票。");
            lv_obj_set_style_text_color(no_ticket_label, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
            lv_obj_set_style_text_font(no_ticket_label, &ui_font_size20, LV_PART_MAIN);
            lv_obj_set_align(no_ticket_label, LV_ALIGN_CENTER);
            lv_obj_update_layout(ui_PanelTicketListContainer);
        }
        progress = 0;
    }
}

void confirm_print_btn_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("点击了 '确认出票' 按钮。\n");
        fflush(stdout);

        int selected_count = 0;
        for(int i = 0; i < g_num_user_tickets; i++) {
            if(g_user_tickets[i].selected_for_print) {
                selected_count++;
            }
        }

        if(selected_count == 0) {
            show_message_box("提示", "请先选择要出票的电影票！", ui_PanelPrintTicketMessageBox,
                             ui_LabelPrintTicketMessageBoxTitle, ui_LabelPrintTicketMessageBoxMessage);
            printf("没有选中的票进行出票。\n");
            fflush(stdout);
            return;
        }

        lv_obj_clear_flag(ui_PanelPrintAnimation, LV_OBJ_FLAG_HIDDEN);
        lv_obj_move_foreground(ui_PanelPrintAnimation);
        lv_bar_set_value(ui_ProgressBarPrint, 0, LV_ANIM_OFF);
        lv_label_set_text(ui_LabelPrintStatus, "正在准备打印...");

        lv_timer_create(print_animation_timer_cb, 200, NULL);
        printf("开始出票动画。\n");
        fflush(stdout);

        lv_obj_add_event_cb(lv_scr_act(), screen_clicked_event_cb, LV_EVENT_CLICKED, NULL);
    }
}
